define(['./module'],function(advertisemodule){
	'use strict';
	
	advertisemodule.controller('advertise',ServerSaveAdvertise);
	function ServerSaveAdvertise($scope,$http,$location,Upload,$timeout){
	
		$scope.$watch('files',function(){
			$scope.upload($scope.files);
		});
		$scope.allupimgs=[];
		$scope.upload=function(files){
			if(files&&files.length){
				for(var i=0;i<files.length;i++){
					var file=files[i];
					var filename=files[i].name;
					if(!file.$error){
						Upload.upload({
							url:'../mall/files/ajaxFileUploadsImgs.action',
							data:{
								file:file,
								'filename':filename
							}
						}).progress(function (evt) {
		                    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
		                    $scope.progress=progressPercentage;
		                }).success(function (data, status, headers, config) {
		                    $timeout(function() {
		                    	if(data.sucflag){
		                    		$scope.allupimgs.push(data);
		                    	}
		                    });
		                    
		                });
					}
				}
			}
		}
		
		$scope.remove=function(index){
			$scope.allupimgs.splice(index,1);
		}
		
		$scope.gtparams=[];
		$scope.index=1;
		//通过location中的operate参数区分操作行为
		var operate=$location.search().operate;
		if(operate!=undefined&&operate=="save"){
			//控制保存按钮显示
			$scope.savebtn={show:true};
			$scope.title='添加广告信息';
			$scope.status="1";
			$scope.showWhere="3";
			//短期广告
			$scope.showtype="0";
			//默认高度
			$scope.height=200;
			//默认宽度
			$scope.width=200;
			$scope.type="2";
			$scope.sort=1;
			$scope.reservationtimeshow=true;
			
			$scope.$watch('showTag',function(){
				$scope.code=$scope.showTag;
			});
			
			
			$scope.showtypechange=function(){
				if($scope.showtype=="0"){
					$scope.reservationtimeshow=true;
				}else{
					$scope.reservationtimeshow=false;
				}
			}
			
			
			//保存数据方法
			$scope.save=function(){
				if($scope.alt==undefined){
					$scope.errors={
							show:true,
							msg:'请输入广告说明'
					}
					return false;
				}
				if($scope.href==undefined){
					$scope.errors={
							show:true,
							msg:'请输入广告链接'
					}
					return false;
				}
				if($scope.showTag==undefined){
					$scope.errors={
							show:true,
							msg:'请输入展示位置标记'
					}
					return false;
				}
				if($scope.showtype=="0"){
					if($scope.reservationtime==undefined){
						$scope.errors={
								show:true,
								msg:'请选择广告持续时间'
						}
						return false;
					}
				}else{
					$scope.reservationtime="";
				}
				if($scope.code==undefined){
					$scope.errors={
							show:true,
							msg:'请输入标记码'
					}
					return false;
				}
				var mainimg = angular.toJson($scope.allupimgs);
				$http({
					method:'POST',
					url:'../mall/advertise/save.action',
					data:{
						'showTag':$scope.showTag,
						'href':$scope.href,
						'reservationtime':$scope.reservationtime,
						'height':$scope.height,
						'width':$scope.width,
						'sort':$scope.sort,
						'showWhere':$scope.showWhere,
						'alt':$scope.alt,
						'showtype':$scope.showtype,
						'type':$scope.type,
						'mainimg':mainimg,
						'code':$scope.code,
						'status':$scope.status
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.info={
								show:true,
								msg:'广告信息添加成功'
						}
						$location.path("/advertisement");
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}
		
		}
		
		//如果operate是edit则执行保存行为
		if(operate=='edit'){
			var id=$location.search().id;
			if(id!=undefined&&id!=""){
				$http({
					method:'POST',
					url:'../mall/advertise/find.action',
					data:{
						'advertiseid':id
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.title='正在对广告--'+data.bean.alt+'--进行编辑';
						$scope.alt=data.bean.alt;
						$scope.href=data.bean.href;
						$scope.showTag=data.bean.showTag;
						$scope.showtype=data.bean.showtype;
						if($scope.showtype=="0"){
							$scope.reservationtimeshow=true;
							$scope.reservationtime=data.reservationtime;
						}
						$scope.height=data.bean.height;
						$scope.width=data.bean.width;
						$scope.type=data.bean.type;
						$scope.showWhere=data.bean.showWhere;
						$scope.code=data.bean.code;
						$scope.sort=data.bean.sort;
						$scope.allupimgs.push(data.ifb);
						$scope.status=data.bean.status;
						$scope.updatebtn={show:true};
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
				//更新数据方法
				$scope.update=function(){
					if($scope.alt==undefined){
						$scope.errors={
								show:true,
								msg:'请输入广告说明'
						}
						return false;
					}
					if($scope.href==undefined){
						$scope.errors={
								show:true,
								msg:'请输入广告链接'
						}
						return false;
					}
					if($scope.showTag==undefined){
						$scope.errors={
								show:true,
								msg:'请输入展示位置标记'
						}
						return false;
					}
					if($scope.showtype=="0"){
						if($scope.reservationtime==undefined){
							$scope.errors={
									show:true,
									msg:'请选择广告持续时间'
							}
							return false;
						}
					}else{
						$scope.reservationtime="";
					}
					if($scope.code==undefined){
						$scope.errors={
								show:true,
								msg:'请输入标记码'
						}
						return false;
					}
					var mainimg = angular.toJson($scope.allupimgs);
					$http({
						method:'POST',
						url:'../mall/advertise/update.action',
						data:{
							'advertiseid':id,
							'href':$scope.href,
							'showTag':$scope.showTag,
							'reservationtime':$scope.reservationtime,
							'height':$scope.height,
							'width':$scope.width,
							'sort':$scope.sort,
							'showWhere':$scope.showWhere,
							'alt':$scope.alt,
							'showtype':$scope.showtype,
							'type':$scope.type,
							'mainimg':mainimg,
							'code':$scope.code,
							'status':$scope.status
						}
					}).
					success(function(data,status,headers,config){
						if(data.sucflag){
							$scope.info={
									show:true,
									msg:'广告信息更新成功'
							}
							$location.path("/advertisement");
						}
					}).
					error(function(data,status,headers,config){
						$scope.errors={
								show:true,
								msg:'系统异常'
						}
					});
				}
			}
		
		}
	}
	/*=====End Of Save and Edit AdvertiseT=====*/
	
	/*=====Begin Of Find List AdvertiseT=====*/
	advertisemodule.controller('advertiselist',ServerAdvertiseListCtrl);
	//查询列表数据
	function ServerAdvertiseListCtrl($http,$location,$compile,$scope,$rootScope,$resource,DTOptionsBuilder,DTColumnBuilder,DTAjaxRenderer){
		var vm=this;
		vm.message='';
		vm.someClickHandler = someClickHandler;
		vm.selected={};
		vm.selectAll=false;
		vm.toggleAll=toggleAll;
		vm.toggleOne=toggleOne;
		vm.dtInstance={};
		var titleHtml='<input type="checkbox" ng-model="showCase.selectAll" ng-click="showCase.toggleAll(showCase.selectAll,showCase.selected)">';
		vm.dtOptions=DTOptionsBuilder.newOptions().withOption('ajax',{
			type:'POST',
			url:'../mall/advertise/findByPage.action',
			dataSrc:'data'
		})
		.withOption('processing',true)
		.withOption('paging',true)
		.withOption('serverSide',true)
		.withOption('createdRow',function(row,data,dataIndex){
			$compile(angular.element(row).contents())($scope);
		})
		.withOption('headerCallback', function(header) {
            if (!$scope.headerCompiled) {
                $scope.headerCompiled = true;
                $compile(angular.element(header).contents())($scope);
            }
        })
        .withOption('stateSave', true)
        .withOption('rowCallback',rowCallback)
		.withPaginationType('full_numbers')
		.withLanguageSource('./app/language/chinese.json')
		
		$scope.$on('handleRequest',function(){
			
		});
		
		vm.dtColumns=[
		              DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function(data,type,full,meta){
		            	  vm.selected[full.id]=false;
		            	  return '<input type="checkbox" ng-model="showCase.selected['+data.id+']" ng-click="showCase.toggleOne(showCase.selected)">';
		              }),
		              DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
		              DTColumnBuilder.newColumn('alt').withTitle('广告说明').notSortable(),
		              DTColumnBuilder.newColumn(null).withTitle('广告图').notSortable().renderWith(imgHtml),
		              DTColumnBuilder.newColumn('showTag').withTitle('展示位置标记').notSortable(),
			          DTColumnBuilder.newColumn('showtype').withTitle('广告时效').notSortable(),
			          DTColumnBuilder.newColumn('time').withTitle('持续时间').notSortable(),
			          DTColumnBuilder.newColumn('showWhere').withTitle('展现位置').notSortable(),
			          DTColumnBuilder.newColumn('sort').withTitle('排序').notSortable(),
			          DTColumnBuilder.newColumn('status').withTitle('状态').notSortable(),
			          DTColumnBuilder.newColumn('updatetime').withTitle('更新时间').notSortable(),
			          DTColumnBuilder.newColumn('version').withTitle('版本号').notSortable(),
			          DTColumnBuilder.newColumn(null).withTitle('操作').notSortable().renderWith(actionHtml)];
		function imgHtml(data,type,full,meta){
			return '<img style="width:50px;height:50px;" ng-src="'+data.mainimg+'" alt="Photo" />';
		}
		function actionHtml(data,type,full,meta){
			return '<button class="btn btn-warning" ng-click="edit('+data.id+')"><i class="fa fa-edit"></i></button>';
		}
		
		function reloadData(){
			var resetPaging = false;
	        vm.dtInstance.reloadData(callback, resetPaging);
		}
		function callback(data){
		}
		
		//表格中编辑按钮
		$scope.edit=function(id,name){
			$location.path('/advertise').search({'operate':'edit','id':id});
		}
		
		/**
		 * 跳转到添加商品类型和参数页面
		 */
		$scope.save=function(){
			$location.path('/advertise').search({'operate':'save'});
		}
		
		$scope.del=function(){
			var i=0;
			var ids=[];
			angular.forEach(vm.selected, function(data,index,array){
				if(data){
					i++;
					ids.push(index);
				}
			});
			if(i==0){
				$scope.errors={
						show:true,
						msg:'请选择一条记录'
				}
			}else{
				$scope.errors={
						show:false
				}
				//批量删除数据
				var idstrs=ids.join(",");
				$http({
					method:'POST',
					url:'../mall/advertise/del.action',
					data:{
						'ids':idstrs
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.info={
								show:true,
								msg:'批量删除成功'
						}
						reloadData();
					}
					
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}
		}

		/**
		 * 列表全选
		 */
		function toggleAll(selectAll,selectedItems){
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					selectedItems[id]=selectAll;
				}
			}
		}
		/**
		 * 列表单选
		 */
		function toggleOne(selectedItems){
			var me=this;
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					if(!selectedItems[id]){
						me.selectAll=false;
					}
				}
			}
			me.selectAll=true;
		}

		function someClickHandler(info) {
	        vm.message = info.id + ' - ' + info.name;
	    }
		/**
		 * 单击列表某行回调
		 */
		function rowCallback(nRow,aData,iDisplayIndex,iDisplayIndexFull){
			$('td', nRow).unbind('click');
	        $('td', nRow).bind('click', function() {
	            $scope.$apply(function() {
	                vm.someClickHandler(aData);
	            });
	        });
	        return nRow;
		}
	}
	/*=====End Of Find List MemberT=====*/
});